package com.esiag.isidis.fi.pdsteam.service;

import java.util.List;
import java.util.Map;

import com.esiag.isidis.fi.pdsteam.entity.Info;
import com.esiag.isidis.fi.pdsteam.entity.ParsedMessage;
import com.esiag.isidis.fi.pdsteam.entity.RawByteObject;
import com.esiag.isidis.fi.pdsteam.entity.TramConfig;

public class MessageConstructor {

	@SuppressWarnings("rawtypes")
	public ParsedMessage construct(RawByteObject rawByteObject,
			TramConfig tramConfig) {
		byte[] bytes = rawByteObject.getBytes();
		ParsedMessage message = new ParsedMessage();
		List<Info> listInfo = tramConfig.getListInfo();
		Map<String, Object> map = message.getList();
		int end = 0;
		int start = 0;
		int i = 0;
		for (Info info : listInfo) {
			i++;
			String libelle = info.getLibelle();
			start = end;
			end = info.getLongueur() + end;

			if (end > bytes.length)
				break;
			String type = info.getType();
			String maChaine = convertByteArrayToString(bytes, start, end);
			Object object = fillObject(maChaine, type);
			map.put(libelle, object);
		}
		return message;
	}

	private Object fillObject(String maChaine, String type) {
		// test sur le type d'objet
		Object object = null;
		if (type.equals("String"))
			object = fillString(maChaine);
		if (type.equals("Integer"))
			object = fillInt(maChaine);
		return object;
	}

	private String fillString(String maChaine) {
		String output = "";
		for (int i = 0; i <= maChaine.length() - 8; i += 8) {
			int k = Integer.parseInt(maChaine.substring(i, i + 8), 2);
			System.out.println("k: " + k);
			output += (char) k;
		}
		return output;
	}

	private Integer fillInt(String maChaine) {
		Integer nombre = Integer.parseInt(maChaine, 2);
		return nombre;
	}

	public String convertByteArrayToString(byte[] bytes, int start, int end) {
		String result = "";
		for (int i = start; i < end; i++) {
			result += bytes[i];
		}
		return result;
	}
}
